package com.gobuy.system.controller;


import com.gobuy.common.pojo.Result;
import com.gobuy.common.pojo.StatusCode;
import com.gobuy.system.pojo.Admin;
import com.gobuy.system.service.AdminService;
import com.gobuy.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;
    /***
     * 新增数据
     * @param admin
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true, StatusCode.OK,"添加成功");
    }

    @GetMapping
    public Result<List<Admin>> findAll(){
        List<Admin> adminList = adminService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",adminList) ;
    }

    /**
     * @RequestBody 针对 post请求，将请求体的参数 封装到实体类
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin){
        boolean loginFlag = adminService.login(admin);
        if(loginFlag){
            //密码正确
            //生成jwt令牌，返回到客户端
            Map<String,String> info = new HashMap<>(16);
            info.put("username",admin.getLoginName());
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getLoginName(), null);
            info.put("token",jwt);
            //token返回给前端,由前端决定保存在哪
            return new Result(true,StatusCode.OK,"登录成功",info);
        }else{
            return new Result(false,StatusCode.ERROR,"登录失败");
        }
    }

}
